package com.rututor.server.blob;

import java.io.IOException;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.rututor.server.dao.TutorApplicationsDAO;
import com.rututor.server.util.EmailServices;

public class UploadApplyTutorFile extends HttpServlet {
	private static final Logger Log  = Logger.getLogger(UploadApplyTutorFile.class.getName()); //Need to set properties to use logging
	private static final long serialVersionUID = 5143425222083183436L;
	private BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		String name = req.getParameter("name");
		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
		BlobKey blobKey = blobs.get("myFile");
		
		
		String blobKeyString;
		if (blobKey == null) {
			blobKeyString = "";
		} else {
			blobKeyString = blobKey.getKeyString();
		}
		TutorApplicationsDAO application = new TutorApplicationsDAO();
		
		Long appId = application.insertApplication(name, blobKeyString);
		if (appId == null) {
			appId = new Long(-1);
		}
		System.out.println("Sending new tutor application email...");
		Log.info("Sending new tutor application email...");
		EmailServices.sendNewApplicationEmail(name, blobKeyString);
		res.sendRedirect("/ApplyTutor.jsp?blob-key=" + blobKeyString
				+ "&application-key=" + appId);
	}
}
